package mutiyi;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

/**
 * Author:yang
 * Date:2024-03-06 10:59
 * MQTT客户端
 */
public class MQClient {
    private MqttClient client;
    private String broker;
    private String clientId;
    private MemoryPersistence persistence;
    private String username = "root";
    private String password = "123456";

    public MQClient(String broker, String clientId) {
        this.broker = broker;
        this.clientId = clientId;
        this.persistence = new MemoryPersistence();

        try {
            // 创建MQTT客户端实例对象
            this.client = new MqttClient(broker, clientId, persistence);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /*
    连接
     */
    public void connect() {
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setUserName(username);
        mqttConnectOptions.setPassword(password.toCharArray());
        try {
            // 连接到MQTT代理
            this.client.connect(mqttConnectOptions);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /*
    断开连接
     */
    public void disconnect() {
        try {
            // 断开连接
            this.client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /*
    订阅
     */
    public void subscribe(String topic) {
        try {
            // 订阅主题
            this.client.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /*
    发布消息
     */
    public void publish(String topic, String message) {
        try {
            // 创建消息
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttMessage.setQos(2);

            // 发布消息
            this.client.publish(topic, mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
